<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card卡片 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      >
      </el-alert> params
      <div style="margin:15px 0;">
        <span style="font-size:14px">选择商品分类：</span>
        <el-cascader
          v-model="SelectorValue"
          :options="CateClassifyData"
          :props="GoodsClassifyConfig"
          @change="handleChange"
        ></el-cascader>
      </div>
      <el-tabs v-model="active" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="IsForbidParams"
            @click="addParams"
            >添加参数</el-button
          >
          <!-- 表格 -->
          <el-table :data="ParamsData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="570">
            </el-table-column>
            <el-table-column label="操作" width="570"
              >0
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="redactDynamic(scope.row)"
                  >编辑</el-button
                >

                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="IsForbidParams"
            @click="addParams"
            >添加属性</el-button
          >
          <el-table :data="ParamsData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="570">
            </el-table-column>
            <el-table-column label="操作" width="570">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="redactStatic(scope.row)"
                  >编辑</el-button
                >

                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 编辑动态表格参数 -->
    <el-dialog
      title="修改动态参数"
      :visible.sync="redactDynamicDisplay"
      width="50%"
    >
      <el-form
        ref="DynamicRef"
        :model="editDynamic"
        label-width="80px"
        :rules="DynamicParamsRules"
      >
        <el-form-item label="活动参数" prop="attr_name">
          <el-input v-model="editDynamic.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="redactDynamicDisplay = false">取 消</el-button>
        <el-button type="primary" @click="YesEditDynamic()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑静态属性参数 -->
    <el-dialog
      title="修改静态属性"
      :visible.sync="redactStaticDisplay"
      width="50%"
    >
      <el-form
        ref="StaticRef"
        :model="editStatic"
        label-width="80px"
        :rules="StaticParamsRules"
      >
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="editStatic.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="YesEditStatic = false">取 消</el-button>
        <el-button type="primary" @click="YesEditStatic()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加参数 -->
    <el-dialog
      :title="'添加' + addText"
      :visible.sync="AddParamsDisplay"
      width="50%"
      @close="AddParamsClose"
    >
      <el-form
        ref="addParamsRef"
        :model="addParamsData"
        label-width="80px"
        :rules="addParamsDataRules"
      >
        <el-form-item :label="addText" prop="attr_name">
          <el-input v-model="addParamsData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddParamsDisplay = false">取 消</el-button>
        <el-button type="primary" @click="YesAddParams()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      CateClassifyData: [],
      // 级联数据配置信息
      GoodsClassifyConfig: {
        // 这个值是级联选择的值也就是v-model双向绑定的值
        value: "cat_id",
        expandTrigger: "hover",
        label: "cat_name",
        children: "children"
      },
      // 级联选择的值
      SelectorValue: [],
      // 动态参数和动态属性，它们之间活跃的值
      active: "many",
      // 参数数据
      ParamsData: [],
      // 编辑动态参数的显示与隐藏
      redactDynamicDisplay: false,
      redactStaticDisplay: false,
      // 动态参数验证规则
      DynamicParamsRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }]
      },
      // 修改动态属性的数据
      editDynamic: {
        attr_name: ""
      },
      // 修改静态属性的数据
      editStatic: {
        attr_name: ""
      },
      // 存放修改动态属性的数据
      StoreeditDynamic: {},
      // 存放修改静态属性的数据
      saveEditStatic: {},
      // 静态属性验证规则
      StaticParamsRules: {
        attr_name: [
          { required: true, message: "请输入静态参数", trigger: "blur" }
        ]
      },
      // 保存修改属性后存的数据
      modificationData: {},
      // 控制添加参数的显示与隐藏
      AddParamsDisplay: false,
      // 添加参数的数据
      addParamsData: {},
      // 添加参数的校验规则
      addParamsDataRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getGoodsParams();
  },
  methods: {
    async getGoodsParams() {
      const { data: ret } = await this.$http.get("/categories");
      if (ret.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.CateClassifyData = ret.data;
    },
    handleChange() {
      // 只能选择三级商品 如果没有选择三级商品那么它最终选择的要为空
      if (this.SelectorValue.length !== 3) {
        this.SelectorValue = [];
      }
      this.getGoodsClassfiyParams();
      // console.log(this.ParamsData);
    },
    handleTabsClick() {
      console.log(this.active);
      this.getGoodsClassfiyParams();
    },
    // 获取商品分类数据
    async getGoodsClassfiyParams() {
      const { data: ret } = await this.$http.get(
        `/categories/${this.SelectorValue[2]}/attributes`,
        {
          params: { sel: this.active }
        }
      );

      if (ret.meta.status !== 200) {
        return this.$message.error("获取参数失败");
      }
      // 筛选数据，防止得到一个空的数据，从而渲染一个空的 tag标签
      ret.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 给每个参数的展开行添加 tab 自己的数据
        item.inputVisible = false;
        item.inputValue = "";
      });
      this.ParamsData = ret.data;

      console.log(this.ParamsData);
    },
    // 编辑动态参数
    redactDynamic(row) {
      this.StoreeditDynamic = row;
      this.editDynamic.attr_name = row.attr_name;
      console.log("a");
      this.redactDynamicDisplay = true;
    },
    // 编辑静态属性
    redactStatic(row) {
      this.saveEditStatic = row;
      this.editStatic.attr_name = row.attr_name;
      this.redactStaticDisplay = true;
    },
    // 确定提交修改动态属性
    YesEditDynamic() {
      this.$refs.DynamicRef.validate(async valid => {
        if (!valid) {
          return;
        }
        // const { data: ret } = await this.$http.put(
        //   `/categories/${this.StoreeditDynamic.cat_id}/attributes/${this.StoreeditDynamic.attr_id}`,
        //   {
        //     attr_name: this.editDynamic.attr_name,
        //     attr_sel: this.StoreeditDynamic.attr_sel,
        //     attr_vals: this.StoreeditDynamic.attr_vals
        //   }
        // );

        // this.modificationData = ret;
        // console.log(ret);
        // console.log(this.modificationData);
        await this.ModificationParamsData(
          this.StoreeditDynamic.cat_id,
          this.StoreeditDynamic.attr_id,
          this.editDynamic.attr_name,
          this.StoreeditDynamic.attr_sel,
          this.StoreeditDynamic.attr_vals
        );
        // console.log(this.modificationData)
        // if (this.modificationData.meta.status !== 200) {
        //   return this.$message.error("修改动态参数失败");
        // }
        // this.$message.success("修改参数成功！");
        // this.getGoodsClassfiyParams();
        // console.log("刷新");

        this.redactDynamicDisplay = false;
      });
    },
    // 确定提交修改静态属性
    YesEditStatic() {
      this.$refs.StaticRef.validate(async valid => {
        console.log(valid);
        if (!valid) {
          return;
        }
        await this.ModificationParamsData(
          this.saveEditStatic.cat_id,
          this.saveEditStatic.attr_id,
          this.editStatic.attr_name,
          this.saveEditStatic.attr_sel,
          this.saveEditStatic.attr_vals
        );
        this.redactStaticDisplay = false;
      });
    },
    // 封装编辑参数名称后的请求函数
    async ModificationParamsData(
      class_id,
      attr_id,
      attr_name,
      attr_sel,
      attr_vals
    ) {
      const { data: ret } = await this.$http.put(
        `/categories/${class_id}/attributes/${attr_id}`,
        {
          attr_name: attr_name,
          attr_sel: attr_sel,
          attr_vals: attr_vals
        }
      );
      this.modificationData = ret;
      if (this.modificationData.meta.status !== 200) {
        return this.$message.error("修改动态参数失败");
      }
      this.$message.success("修改参数成功！");
      this.getGoodsClassfiyParams();
      // console.log(this.modificationData.meta.status);
    },
    // 添加参数
    addParams() {
      this.AddParamsDisplay = true;
    },
    // 关闭添加属性输入框
    AddParamsClose() {
      this.addParamsData = {};
    },
    // 确定添加参数发送请求
    YesAddParams() {
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) {
          return;
        }
        const { data: ret } = await this.$http.post(
          `categories/${this.SelectorValue[2]}/attributes`,
          {
            attr_name: this.addParamsData.attr_name,
            attr_sel: this.active
          }
        );
        // console.log(ret);
        if (ret.meta.status !== 201) {
          return this.$message.error("添加参数失败！");
        }
        this.$message.success("添加参数成功！");
        this.getGoodsClassfiyParams();
        this.AddParamsDisplay = false;
      });
    },
    // 删除参数
    async deleteParams(row) {
      // console.log(row);
      const Result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);

      if (Result !== "confirm") {
        return this.$message.info("取消删除");
      }
      const { data: ret } = await this.$http.delete(
        `categories/${this.SelectorValue[2]}/attributes/${row.attr_id}`
      );
      if (ret.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功！");
      this.getGoodsClassfiyParams();
    },
    // 失去焦点函数
    async handleInputConfirm(row) {
      row.inputVisible = false;
      // 这里做个数据请求（1.做个判断，如果input表单输入的值为空，就不请求）
      if (row.inputValue.trim().length == 0) {
        row.inputValue = "";
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      this.getAddDeleteAn(row);
    },

    // 点击显示input
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 关闭分类参数展开行回调
    async handleClose(index, row) {
      row.attr_vals.splice(index, 1);
      this.getAddDeleteAn(row);
    },
    // 获取分类参数展开的删除或者添加的数据请求

    async getAddDeleteAn(row) {
      const { data: ret } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (ret.meta.status !== 200) {
        return this.$message.error("添加数据失败！");
      }
    }
  },
  computed: {
    IsForbidParams() {
      if (this.SelectorValue.length !== 3) {
        return true;
      }
      return false;
    },
    addText() {
      if (this.active == "many") {
        return "动态参数";
      }
      return "静态属性";
    }
  }
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 130px;
}
</style>
